package com.bittech.everything.core.index.impl;

import com.bittech.everything.config.EverythingConfig;
import com.bittech.everything.core.index.FileScan;
import com.bittech.everything.core.interceptor.FileInterceptor;

import java.io.File;
import java.nio.file.Paths;
import java.util.LinkedList;
import java.util.List;

/**
 * Author: secondriver
 * Created: 2018/9/26
 */
public class FileScanImpl implements FileScan {
    
    private List<FileInterceptor> interceptors = new LinkedList<>();
    
    private EverythingConfig everythingConfig = EverythingConfig.getInstance();
    
    @Override
    public void index(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return;
        }
        for (String exclude : everythingConfig.getExcludePaths()) {
            if (Paths.get(path).startsWith(exclude)) {
                return;
            }
        }
        if (file.isDirectory()) {
            File[] list = file.listFiles();
            if (list != null) {
                for (File f : list) {
                    index(f.getPath());
                }
            }
        }
        for (FileInterceptor interceptor : interceptors) {
            interceptor.applyFile(file);
        }
    }
    
    @Override
    public void interceptor(FileInterceptor fileInterceptor) {
        this.interceptors.add(fileInterceptor);
    }
}
